package com.core.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

/**
 * LoginInterceptor
 */
public class LoginInterceptor implements Interceptor {
	/**
	 * 要检查的url类型
	 */
	private String[] checkUrls = { ".jhtml" , ".jsp" };
	/**
	 * 不要检查的url类型
	 */
	private String[] escapeUrls = { "login.jhtml" , "login.jsp"};

	public void intercept(ActionInvocation me) {
		Controller controller = me.getController();
		HttpServletRequest request = controller.getRequest();
		String url = request.getRequestURI();
		if (check(url, checkUrls)) {
			if (!check(url, escapeUrls)) {
				if (request.getSession().getAttribute("LOGIN_USER") == null) {
					controller.redirect("/admin/login.jsp");
					return ; 
				}
				//防止用户从地址栏内直接输入权限外的地址
				if(!url.endsWith("main.jhtml")){
					String referer = ""; 
					referer = request.getHeader("REFERER"); //获取父url--如果不是直接输入的话就是先前的访问过来的页面，要是用户输入了，这个父url是不存在的  
			        if(StrKit.isBlank(referer)){ //判断如果上一个目录为空的话，说明是用户直接输入url访问的  
			        	controller.redirect("/admin/login.jsp");
			        	return ; 
			        }
				}
			}
		}
		me.invoke();
	}
	
	private boolean check(String element, String[] elements) {
		for (String e : elements) {
			if (element.endsWith(e)) {
				return true;
			}
		}
		return false;
	}

}
